Skip to content

Native prefill bridge: multi-model support - #3

Open
TheTom wants to merge 27 commits into
ek/tom-eric-moe-tuningfrom
pr/native-prefill-multimodel
Open

TheTom wants to merge 27 commits into
ek/tom-eric-moe-tuningfrom
pr/native-prefill-multimodel

Conversation

@TheTom

@TheTom TheTom commented Apr 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Fix KV cache dtype mismatch (bfloat16→float16) that caused garbage output for all dense models
  • Add native prefill bridge support for 8 model architectures
  • Add YaRN RoPE, MXFP4 quantization mode, and attention sinks for GPT-OSS
  • Add fused QKV/gate_up weight splitting for Phi-4
  • Add SSM h=64 and GatedDelta Hk=16 kernel instantiations
  • Gemma-4 v2 bridge: optional PLE, optional v_proj (k_eq_v), statically linked
  • Standalone MLX float16 sum reduction bug repro

Models working through bridge

Model Arch Status
Mistral-7B llama ✅
Llama-3.2-3B llama ✅
Qwen2.5-3B qwen2 ✅
Qwen3-4B qwen3 ✅
Phi-4-mini phi3 (fused QKV) ✅
Qwen3-Coder-30B qwen3_moe ✅
MiniMax M2 minimax_m2 ✅
GPT-OSS-20B gpt_oss (YaRN+MXFP4+sinks) ✅

Models running (Swift prefill, kernel fixes)

Model Fix
Nemotron-Cascade-30B SSM kernel h=64 instantiation
Qwen3.5-2B GatedDelta kernel Hk=16 instantiation

TODO

  • Gemma-4-26B: v2 bridge builds all 30 layers but forward hits matmul shape error (quantization constant mismatch)
  • gemma-3-4b: VLM packaging blocks text-only bridge path

Test plan

  • Verified coherent output for all 8 bridge models via MLXServer
  • Hidden state comparison (bridge vs Swift) for Mistral and GPT-OSS
  • No regression on MoE models (Qwen3-Coder)
  • Perf benchmarks at higher context lengths

🤖 Generated with Claude Code

Rebase notes

  • Rebase onto pr/mlx-server once that PR lands — this PR temporarily includes MLXServer sources for testing, but the canonical MLXServer lives in that separate PR.

TheTom and others added 8 commits April 13, 2026 23:49
Core C++ bridge (generic_prefill.cpp) supporting multiple model
architectures through runtime config dispatch. Key features:

- std::optional-based structs (QuantizedLinear, Norm, Embedding,
  KVCache, Layer) to avoid MLX array default-init overhead
- KV cache dtype inferred from model's quantization scales to match
  Swift's expected dtype (float16 or bfloat16)
- Chunked prefill with periodic eval barriers
- Auto-detection of quantization bits from weight/scales shape ratio
- Support for QK norm (before/after reshape), custom attention scale
- MoE forward with gather_qmm, expert sorting, sigmoid/softmax routing
- YaRN RoPE frequency computation for extended context models
- MXFP4 quantization mode with optional biases
- Attention sinks support passed through to SDPA
- Fused weight splitting (QKV, gate_up) for Phi3 and GPT-OSS
- Gemma-3 builder with 4-norm pattern, GELU, sliding window RoPE
- GPT-OSS builder with MoE expert dispatch and YaRN

Also includes standalone MLX float16 sum reduction bug repro
(mlx_allocator_repro.cpp).

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add NATIVE_PREFILL integration to prepare() for:
- Llama/Mistral (model_type=generic)
- Qwen2/Qwen2.5 (model_type=qwen2, with attention bias)
- Qwen3 dense (model_type=qwen3, with QK norm)

Also adds GenericPrefillBridge singleton (MiniMaxM2.swift) with
ensureInitialized/runAndInjectKV for shared bridge lifecycle.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Wire Phi3 architecture (model_type=phi3) with bridge support for
fused qkv_proj and gate_up_proj weight splitting at build time.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Fix rms_norm_eps and rope_theta serialization in Qwen3MoE config
JSON — use String(format:) instead of bare Double() interpolation
which produced unparseable values like 'Double(1e-06)'.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Wire GPT-OSS-20B (model_type=gpt_oss) with full bridge support:
- YaRN RoPE with per-dimension frequency correction
- MXFP4 quantization mode with auto-detected group_size
- Attention sinks passed through to SDPA
- Fused gate_up_proj splitting for MoE expert weights
- Mixed quantization: Q8 affine attention + MXFP4 MoE experts

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Gemma-3: Add bridge integration to prepare() (blocked by VLM
model packaging — text-only config lacks required head counts).

Gemma-4 v2 bridge:
- PLE (Per-Layer Embeddings) now optional for models without it
- v_proj optional for k_eq_v attention layers (V=K)
- Statically linked via SPM instead of dlopen dylib
- TODO: forward matmul shape error needs investigation

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add --repro-allocator flag for standalone MLX float16 reduction
bug repro. Update imports for NativePrefillBridge module.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom
TheTom force-pushed the pr/native-prefill-multimodel branch from f7ad8ac to 1f8a765 Compare April 14, 2026 04:51
TheTom and others added 4 commits April 13, 2026 23:51
Keep prebuilt dylibs in repo for backward compatibility with
dlopen-based loading paths.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Simplify make_embedding(): remove unnecessary add-zero copy workaround.
  Swift arrays already have pinned GPU buffers; direct reference + eval
  is sufficient.
- Fix MoE routing: use raw gate logits for argpartition (matching Swift's
  implementation) instead of post-softmax scores. Functionally equivalent
  since softmax is monotonic, but avoids unnecessary graph nodes.
- Add Qwen prefill optimization analysis doc with baseline measurements
  for Qwen2.5-3B, Qwen3-4B, and Qwen3-Coder-30B MoE.

Bridge matches Swift within ~3% for all Qwen architectures. The remaining
gap is from eval barrier synchronization (required for correctness).

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Multi-slot inference server with:
- OpenAI /v1/chat/completions API (streaming + non-streaming)
- Prompt-prefix KV cache with session management
- Parallel inference slots (llama-server style)
- Auto-configured session limits based on available RAM
- Sliding window and full attention cache support
- Tool calling with XML-based function invocation
- Chat template rendering via swift-transformers

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Python script for testing multi-session KV cache behavior:
- Prompt-prefix cache hit/miss verification
- Session eviction under memory pressure
- Concurrent slot utilization
- Cache metrics validation

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom
TheTom force-pushed the pr/native-prefill-multimodel branch from d39e173 to 7fa4506 Compare April 14, 2026 14:43
TheTom and others added 7 commits April 14, 2026 10:27
ModelConfiguration(directory:) for paths starting with / or ~,
fixes .fileNotFound("main") when benchmarking local models.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add prefill_bridge_qwen.cpp — self-contained Qwen-family bridge for
Qwen2, Qwen3, and Qwen3-MoE with tunable eval cadence (QWEN_EVAL_CADENCE
env var) and softmax-only MoE routing. Changes here won't risk regressions
on other model families.

Rename prefill_bridge_v2 → prefill_bridge_gemma and pb2_* → gemma_* for
consistent naming across all three bridges:
  - generic_prefill.cpp / gp_*       → GenericPrefillBridge (Mistral, Phi, etc.)
  - prefill_bridge_gemma.cpp / gemma_* → GemmaPrefillBridge (Gemma-4)
  - prefill_bridge_qwen.cpp / qwen_*  → QwenPrefillBridge (Qwen family)

Wire Qwen2/3/MoE Swift models to QwenPrefillBridge. Generic bridge
files are untouched — no regression risk for other models.

Benchmarked Qwen3-Coder-30B MoE: 1618/1556/1346 t/s at 1k/4k/8k context,
matching generic bridge baseline within noise.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
… bridge

Add QWEN_PROFILE=1 per-stage profiler with eval+sync barriers for
accurate GPU time attribution. Breaks down all 15 stages including
sub-breakdown of MoE gather_qmm into gate+up, silu, and down.

Profile results for Qwen3-Coder-30B MoE @ 998 tokens:
  - moe_gqmm: 55% (389ms) — pure MLX kernel cost
    - gate+up: 257ms (36%), down: 131ms (18%), silu: 14ms (2%)
  - qkv_proj: 13% (89ms)
  - o_proj: 11% (75ms)
  - sdpa: 6% (42ms)
  - everything else: <2% each

Add experimental fused gate+up (QWEN_FUSE_GATE_UP=1): concatenates
gate/up weights for single gather_qmm call. Measured +1% at 1k but
-3% at 4k — disabled by default since larger N hurts kernel efficiency.

Findings:
  - Eval barrier cadence doesn't affect correctness (tested 4-48)
  - float32 cast for routing gate is required for performance
  - precise softmax costs ~1% — not used (gates are already float32)
  - Bridge-Swift gap (2-4%) is in MLX graph fusion, not bridge overhead

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Two correctness/parity fixes:

1. QK norm: apply BEFORE transpose (matching Swift). Was operating on
   transposed (non-contiguous) tensor layout. Now norms see (B,L,H,D)
   instead of (B,H,L,D), matching the Swift Qwen3MoE implementation.

2. MoE sort: use floor_divide + direct take pattern (matching Swift
   gatherSort). Removes extra astype(uint32) cast and reshape({-1,1})
   on sorted indices that created unnecessary graph nodes vs Swift.

Neither change produced measurable throughput improvement (bridge gap
remains ~3% vs Swift), confirming the gap is in MLX graph fusion
differences, not bridge operation sequence.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Flip all 9 model files from opt-out (!= "0") to opt-in (== "1").
Swift prefill is now the default path. Set NATIVE_PREFILL=1 to
activate the C++ bridge for profiling or A/B testing.

The bridge is ~3% slower than Swift on most models due to MLX graph
fusion differences still being tuned. This keeps the bridge code in
the tree for continued optimization without affecting default behavior.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom
TheTom marked this pull request as ready for review April 14, 2026 17:29
Remove all intermediate eval() barriers from the production forward path.
The full 48-layer forward now builds a single massive lazy graph, matching
Swift's execution pattern. Only the final KV cache eval in qwen_run()
remains (needed for KV injection correctness).

This was the root cause of the 2-4% bridge-vs-Swift gap. Intermediate
eval barriers fragmented the lazy graph, preventing MLX from optimizing
the full computation pipeline (operator fusion, buffer reuse, dispatch
scheduling).

Before (with eval every 8 layers):
  1024: 1616 t/s  |  4096: 1522 t/s  |  8192: 1329 t/s

After (no intermediate barriers):
  1024: 1654 t/s  |  4096: 1579 t/s  |  8192: 1370 t/s

Improvement: +2.4% / +3.7% / +3.1%

Bridge vs Swift gap (paired runs):
  1024: -1.0% (was -3.4%)
  4096: -0.7% (was -3.6%)
  8192: +0.2% (was -2.2%)  ← bridge now matches Swift

Note: eval cadence is still configurable via QWEN_EVAL_CADENCE env var.
The profiled forward path retains per-stage eval barriers for accurate
timing attribution.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Comment thread Package.swift
sources: ["generic_prefill.cpp", "prefill_bridge_gemma.cpp", "prefill_bridge_qwen.cpp", "mlx_allocator_repro.cpp"],
publicHeadersPath: ".",
cxxSettings: [
.unsafeFlags(["-std=c++20"]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C++ 20 required?

}

// Default Swift prefill
let prefillStepSize = max(windowSize ?? 512, 4096)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a remnant from optimizations I had done a while ago before fp32 casts were caught. I was playing with some of this yesterday and I think we might be able to just settle on 2048 which is what I'm passing. TBD.

More of a note as something to come back to to find the optimal value because 4096 isn't I don't think and I also would like to minimize the amount of things people need to configure for optimal tuning. We could have hardware + model profiles instead if there are optimal values for combinations of that.

TheTom and others added 5 commits April 14, 2026 12:48
…cise softmax

Remove the explicit astype(x, float32) before the MoE gate projection
and use softmax(gates, precise=true) instead, matching exactly what
Swift's Qwen3MoE does. This eliminates an unnecessary full-tensor
float32 copy from the lazy graph.

Previous attempt to remove the cast (with eval barriers) showed -2%
regression. Now with barriers removed, the graph structure allows
MLX to optimize the precision handling internally.

Paired @ 1024: Bridge 1659 vs Swift 1674 = -0.9% gap (was -1.0%)
Cumulative improvement from original baseline: +2.7%

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Two changes:

1. Switch final KV cache eval from blocking eval() to async_eval().
   GPU work now overlaps with Swift-side KV injection loop instead of
   blocking the CPU. The arrays materialize lazily when Swift accesses them.

2. Remove .contiguous() on KV injection — bridge concatenate already
   produces contiguous arrays, so this was a redundant copy.

Paired @ 1024: Bridge 1668 vs Swift 1676 = -0.5% (was -1.1%)
Paired @ 8192: Bridge 1383 vs Swift 1373 = +0.7% (bridge wins)

Cumulative improvement from original baseline: +3.2% at 1024

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Some models (Mistral v0.3) don't support system messages in their chat
template. The fallback now removes both tools AND system messages
before retrying, instead of just removing tools.

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add minimax_m2 to LLMModelFactory (was only registered as minimax)
- Benchmark template fallback: strip system prompt for models that
  don't support it (e.g. Mistral v0.3)
- Remove unnecessary .contiguous() on bridge KV injection

Co-Authored-By: tturney@psyguard.ai
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Switch Gemma prefill bridge from SPM static linking to dlopen/dlsym.
SPM's link-time optimizer miscompiles quantized_matmul → matmul,
causing shape errors. dlopen prevents cross-module optimization.

- Gemma4.swift: dlopen bridge with function pointer dispatch
- build-prefill-bridge.sh: compile bridge dylib with clang++ -O3
  using -undefined dynamic_lookup (shares host MLX allocator)
- benchmark.sh: add --bridge flag to pass NATIVE_PREFILL=1

With NAX enabled in mlx-swift (ekryski/mlx-swift#2):
  512 tok: 19,583 tok/s (was 8,342)
  1024 tok: 18,780 tok/s (was 8,683)

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom
TheTom force-pushed the pr/native-prefill-multimodel branch from 5c31ff3 to 10dd5f3 Compare April 14, 2026 21:25
TheTom and others added 2 commits April 14, 2026 16:32
A/B tested on Qwen3-Coder-30B at 1024 context — neutral perf but
safer default for SDPA memory layout.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- [ENV] checks at benchmark start: NAX status, bridge status, Gemma template
- fix-gemma4-template.py: downloads and injects missing chat_template
  from HuggingFace into MLX community Gemma 4 quants
- MLX_BENCH_PROMPT and MLX_BENCH_MAX_TOKENS env var support

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
TheTom added a commit that referenced this pull request May 16, 2026
8-iteration sprint at 16K Qwen2.5-14B-1M-4bit on M5 Max:

Baseline (V20, post compiled-swiglu): 32.7 ms/step decode.
After sprint: 24.8 ms/step pipelined.
Python mlx-lm pipelined: 22.7 ms.

Two real wins, six dead ends:

LANDED:
- Sprint iter #1 — `sysmemSnapshot()` forks `vm_stat` from inside the
  t0..t1 timing window. Moved t1 capture to immediately after eval().
  Save: 2 ms (32.7 → 30.4).
- Sprint iter ekryski#6/ekryski#7 — pipelined decode loop. `model + argMax + asyncEval(tok)`
  then `eval(queuedTok)` of the previous step. Pre-queue one step before
  the timing loop so the GPU is already in flight on the first sample.
  Save: 5.6 ms (30.4 → 24.8). Matches mlx-lm Python's generation_stream
  pipeline pattern.

NO-OP:
- Sprint iter #2 — MLX_METAL_AB=1 / MLX_PERSISTENT_AB=1 env. Qwen2's
  K=5120/13824 doesn't trip qmv_quad fast path (qmv_quad is K=64/128).
- Sprint iter #3 — F83_DECODE_STREAM=1 (decode loop on dedicated GPU
  stream). MLX-swift apparently already isolates kernel dispatch from
  default stream housekeeping at decode shape.
- Sprint iter #4 — MLX_INLINE_ACTIVATION=1 (Gemma FusedGateUpSwitchGLU
  env). Qwen2 doesn't use the FusedGateUpSwitchGLU path.
- Sprint iter ekryski#5 — fused gate+up via sanitize-time weight concat.
  Concat works correctly, but MLX.split apparently dispatches, offsetting
  the matmul saving. Kept in tree as `Qwen2.MLP` now uses `gate_up_proj`
  weight + split; harmless.
- Sprint iter ekryski#8 — removed logLine from inside timing loop. Within noise.

Remaining 2.1 ms / 9% gap to Python pipelined is most likely Swift-side
per-call overhead (Module/@ModuleInfo dispatch, MLXArray ARC) on the
identical MLX C++ kernel path. Closing it requires either a custom
fused MLP Metal kernel binding (the C++ `fused_gate_activation` is in
mlx-swift but has no Swift wrapper) or further reducing the
per-decode-step dispatch count.

Env knobs added (opt-in, default off):
- F83_PIPELINE=1 — pipelined decode loop (new default for this bench
  going forward as it matches mlx-lm Python's measurement style).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants